package com.shop.wk.service.impl;

import com.shop.wk.data.entity.AuRole;
import com.shop.wk.data.entity.AuUser;
import com.shop.wk.service.RoleService;
import com.shop.wk.service.UserService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * @author 日月星辰
 * @date 2020/12/25 20:29
 * @description
 */
@Component(value = "userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 查询用户信息
		AuUser user = userService.getUser(username);
		if (user == null) {
			throw new UsernameNotFoundException("帐号：" + username + " 不存在！");
		}
		List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
		// 查询拥有的角色
		List<AuRole> roles = roleService.getRoleList(user.getId());
		roles.forEach(r -> {
			// security的验证规则需要ROLE_ 对应数据库的角色名称也要以ROLE_XXXX这种形式
			grantedAuthorities.add(new SimpleGrantedAuthority(r.getRoleName()));
		});
		return new User(user.getUsername(), user.getPassword(), grantedAuthorities);
	}

}
